﻿using System;
using System.Collections.Generic;
using System.Linq;
using Neo4jConnect.Rest.Extensions.Sample;
using Newtonsoft.Json.Linq;

namespace Neo4jConnect.Plugins
{
    public static class GraphDatabaseServiceExtensions
    {
        public static IEnumerable<Node> GetAllNodes(this IGraphDatabaseService graphDatabaseService)
        {
            var getAllExtension = graphDatabaseService.RestService.ExtensionManager.GetExtension<GetAllExtension>();
            if (getAllExtension != null)
            {
                string json = getAllExtension.GetAllNodes();

                foreach (JObject jsonNode in JArray.Parse(json).Cast<JObject>())
                {
                    Node node = new Node();
                    node.Init((GraphDatabaseService)graphDatabaseService);
                    node.ReadJson(jsonNode);
                    yield return node;
                }
            }
            else
            {
                throw new Exception("Extension not installed");
            }
        }

        public static IEnumerable<Relationship> GetAllRelationships(this IGraphDatabaseService graphDatabaseService)
        {
            GetAllExtension extension = graphDatabaseService.RestService.ExtensionManager.GetExtension<GetAllExtension>();
            if (extension != null)
            {
                string json = extension.GetAllRelationships();

                foreach (JObject jsonRelationship in JArray.Parse(json).Cast<JObject>())
                {
                    Relationship relationship = new Relationship();
                    relationship.Init((GraphDatabaseService)graphDatabaseService);
                    relationship.ReadJson(jsonRelationship);
                    yield return relationship;
                }
            }
            else
            {
                throw new Exception("Extension not installed");
            }
        }
    }
}
